<?php
namespace app\admin\service;

use exception\FriendlyException;
use think\facade\Env;
use util\AliOss;
use util\RandomUtil;
use think\facade\App;

/**
 * 
 */
class UploadService {

    public static function toPreview($url) {
        $checkUrl = strtolower($url);
        // if(str_ends_with($checkUrl, '.pdf')) return $url;
        // if(str_ends_with($checkUrl, '.jpg')) return $url;
        // if(str_ends_with($checkUrl, '.jpeg')) return $url;
        // if(str_ends_with($checkUrl, '.png')) return $url;
        $newUrl = 'http://preview.kukiiu.com:8012/onlinePreview?url=' . urlencode(base64_encode($url));
        return $newUrl;
    }

    public static function aliOssUpload($bucket, $size = 20) {
        $file = request()->file('file');
        if(!$file) throw new FriendlyException("文件不存在");

        $fileSize = $file->getSize();
        if($fileSize > $size * 1024 * 1024) {
            $max = intval($size);
            throw new FriendlyException("文件不能超过 $max M");
        }

        $fileFullName = $file->getInfo('name');
        $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
        $allowExt = ['pdf', 'jpeg', 'png', 'jpg','ppt', 'mp4'];
        if(!in_array($extension, $allowExt))
            throw new FriendlyException("上传文档格式必须为：". implode(",", $allowExt));
        if(strtolower($extension) != $extension) {
            $fileFullName = str_replace('.'.$extension, '.'.strtolower($extension), $fileFullName);
        }
        $ossName = RandomUtil::random(6) . '_' .  str_replace(array(' ','+'),array('',''),$fileFullName);
        $filePath = $file->getRealPath() ?: $file->getPathname();

        $uploader = new AliOss(Env::get('ALI_OSS_KEY'), Env::get('ALI_OSS_SECRET'), $bucket);
        $uploader->uploadFile($filePath, $ossName);
        $size = $file->getSize();

        return [
            'name' => $fileFullName,
            'ossname' => $ossName,
            'key' => 'oss://'.$ossName,
            'url' => 'oss://'.$ossName,
            'full_url' => 'oss://'.$ossName,
            'size' => $size,
        ];
    }

    public static function aliOssDownload($fileName, $ossName) {
        header("Content-Disposition: attachment;filename=$fileName");
        header("Content-Transfer-Encoding: binary");
        header('Pragma: no-cache');
        header('Expires: 0');
        $uploader = new AliOss(Env::get('ALI_OSS_KEY'), Env::get('ALI_OSS_SECRET'), Env::get('ALI_OSS_BUCKET'));
        $content = $uploader->download($ossName);
        // 发送文件内容
        set_time_limit(0);
        echo $content;
        exit();
    }

    /**
     * @param $size | byte
     * @return string
     * @throws FriendlyException
     */
    public static function localUpload($size = 20, $allowExt = ['pdf', 'jpeg', 'png', 'jpg','ppt', 'mp4']) {
        $file = self::getUploadFile('file', $size, $allowExt);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $publicPath = DS . 'uploads' . DS. date('Ymd') . DS;
        $savePath = App::getRootPath() . 'public' . $publicPath;
        $saveFileName = self::getSaveFileName($file);
        $info = $file->move($savePath, $saveFileName);
        $url = str_replace('\\', '/', ($publicPath . $saveFileName));
        if($info){
            return [
                'name' => $file->getOriginalName(),
                'key' => $info->md5(),
                'url' => $url,
            ];
        }else{
            $errMsg = $file->getError();
            throw new FriendlyException("上传失败: $errMsg");
        }
    }

    public static function localTempUpload() {
        $file = request()->file('file');
        if(!$file) throw new FriendlyException("文件不存在");

        return $_FILES['file']['tmp_name'];
    }

    public static function getUploadFile($name='file', $size = 0, $allowExt = '*') {
        /**
         * @var think\file\UploadedFile
         * getPathname(): 获取临时目录
         */
        $file = request()->file($name);
        if(!$file) throw new FriendlyException("文件不存在");

        $fileSize = $file->getSize();
        if($size != 0 && $fileSize > $size * 1024 * 1024) {
            throw new FriendlyException("文件不能超过 $size M");
        }
        $extension = $file->extension();
        if($allowExt != '*' && is_array($allowExt) && !in_array($extension, $allowExt))
            throw new FriendlyException("上传文档格式必须为:". implode(",", $allowExt));

        return $file;
    }

    private static function getSaveFileName($file, $rule = 'hash') {
        if($rule == 'hash') {
            $extension = $file->extension();
            return md5((string) microtime(true)) . '.' . $extension;
        } else {
            $extension = $file->extension();
            $fileFullName = $file->getOriginalName();
            // 去除空格
            $fileFullName = str_replace(array(' ','+'),array('',''),$fileFullName);
            // 扩展名改为小写
            if(strtolower($extension) != $extension) {
                $fileFullName = str_replace('.'.$extension, '.'.strtolower($extension), $fileFullName);
            }
            return RandomUtil::random(6) . '_' .  $fileFullName;
        }
    }
}
